package com.tp;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.DatePickerDialog;

import android.content.Intent;

import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Create extends CustomWindow implements OnClickListener,
		OnItemClickListener {
	static int select = 0;
	static int index = 0;
	static String data[][] = new String[10][3];
	static EditText startDate;
	static String date;
	static String name;
	Button setDate;
	static EditText tripName;
	Button next, submit;
	TextView _day;
	EditText _des;
	int id_Hotel;
	int id_Res, id_Event;
	static String time;
	static String hotelDes;
	static int id_Trip;
	// for edit trip

	int id_TripHotel;
	static int day = 1;
	static String items[] = { "Khách sạn", "Nhà hàng", "Sự kiện" };
	static int length = 3;
	// public View header;
	// public View footer;
	Activity activity;
	DateFormat fmtDateAndTime = DateFormat.getDateTimeInstance();
	Calendar dateAndTime = Calendar.getInstance();
	DatePickerDialog.OnDateSetListener d = new DatePickerDialog.OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			if (date == null) {
				dateAndTime.set(Calendar.YEAR, year);
				dateAndTime.set(Calendar.MONTH, monthOfYear);
				dateAndTime.set(Calendar.DAY_OF_MONTH, dayOfMonth);
				updateLabel();
				date = startDate.getText().toString();
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.create_header);
		this.icon.setImageResource(R.drawable.create);
		this.title.setText("Tạo hành trình");
		Hotel.flag = 1;
		Restaurant.flag = 1;
		Event.flag = 1;
		_day = (TextView) findViewById(R.id.day);
		_des = (EditText) findViewById(R.id.tripDes);
		startDate = (EditText) findViewById(R.id.create_start_date);
		tripName = (EditText) findViewById(R.id.create_name);
		setDate = (Button) findViewById(R.id.setDate);

		_day.setText("Ngày " + day);

		if (hotelDes != null)
			_des.setText(hotelDes);

		if (name != null)
			tripName.setText(name);
		if (date != null)
			startDate.setText(date);

		ListView list_trip = (ListView) findViewById(R.id.trip_list);
		list_trip.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, items));

		list_trip.setOnItemClickListener(this);

		list_trip.setScrollingCacheEnabled(true);

		setDate.setOnClickListener(this);
		updateLabel();
		// data = new String[10][3];
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.ListActivity#onListItemClick(android.widget.ListView,
	 * android.view.View, int, long)
	 */
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		// TODO Auto-generated method stub
		name = tripName.getText().toString();
		hotelDes = _des.getText().toString();
		if (!tripName.getText().toString().equals("")) {
			if (position == 0) {
				select = 1;
				items[0] = "Khách sạn";
				startActivity(new Intent(this, Hotel.class));
			} else if (position == 1 && select == 1) {
				items[1] = "Nhà hàng";
				startActivity(new Intent(this, Restaurant.class));
			} else if (position == 1 && select == 0) {
				Toast.makeText(this, "Chon khach san tc", Toast.LENGTH_SHORT)
						.show();
			} else if (position == 2 && select == 1) {
				items[2] = "Sự kiện";
				startActivity(new Intent(this, Event.class));
			} else if (position == 2 && select == 0) {
				Toast.makeText(this, "Chon khach san tc", Toast.LENGTH_SHORT)
						.show();
			}
		} else
			Toast.makeText(this, "Hãy nhập tên cho hành trình",
					Toast.LENGTH_SHORT).show();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_create, menu);
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.nextday:
			/*
			 * if (day == 1) { id_Trip = sendTripInfo(); // add basic info of
			 * trip }
			 */
			data[day][0] = items[0];
			data[day][1] = items[1];
			data[day][2] = items[2];
			// addHotel(); // add hotel, res
			day++;
			hotelDes = "";
			items[0] = "Khách sạn";
			items[1] = "Nhà hàng";
			items[2] = "Sự kiện";
			startActivity(new Intent(this, Create.class));
			break;
		case R.id.submit:
			// if (day == 1) {
			id_Trip = sendTripInfo();
			// }
			if (items[0].equals("Khách sạn"))
				day--;
			else {
				data[day][0] = items[0];
				data[day][1] = items[1];
				data[day][2] = items[2];
			}
			// update duration of Trip
			if (id_Trip > 0) {
				updateTrip(id_Trip, day);
			}

			addHotel2(); // add hotel, res
			day = 1;
			// data= new String[10][];
			name = "";
			hotelDes = "";
			items[0] = "Khách sạn";
			items[1] = "Nhà hàng";
			items[2] = "Sự kiện";
			startActivity(new Intent(this, ListTrip.class));
			break;
		}
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

		switch (v.getId()) {
		case R.id.setDate:
			name = tripName.getText().toString();
			// Create.tripName.setText(Create.tripName.getText().toString());
			new DatePickerDialog(Create.this, d,
					dateAndTime.get(Calendar.YEAR),
					dateAndTime.get(Calendar.MONTH),
					dateAndTime.get(Calendar.DAY_OF_MONTH)).show();
			tripName.setText(name);
			break;

		}
	}

	private void updateTrip(int id_Trip, int duration) {
		// TODO Auto-generated method stub
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("id_Trip", Integer
				.toString(id_Trip)));
		postParameters.add(new BasicNameValuePair("duration", Integer
				.toString(duration)));
		// String response = null;
		try {
			CustomHttpClient.executeHttpPost(Constant.host
					+ "/TripController/updateTrip", postParameters);
			/*
			 * String res = response.toString(); res = res.replaceAll("\\s+",
			 * "");
			 */

		} catch (Exception e) {

		}

	}

	private void addHotel2() {
		for (int n = 1; n <= day; n++) {
			// String sub[] = items[0].split("\n");// tach hotel va luu vao mang
			// sub[]
			String m[] = new String[3];
			m[0] = data[n][0];
			m[1] = data[n][1];
			m[2] = data[n][2];
			String sub[] = m[0].split("\n");// tach hotel va luu vao mang sub[]
			// String sub[] = m[0].split("\n");
			for (int i = 1; i < sub.length; i++) {
				Log.v("SUB", sub[i]);
				for (int j = 0; j < Hotel.jArr.length(); j++) {
					try {
						JSONObject json_data = Hotel.jArr.getJSONObject(j); // lay
																			// tung
																			// hotel
																			// trong
																			// DB
						String name2 = json_data.getString("name");
						if (sub[i].equals(name2)) { // so sanh hotel trong DB vs
													// hotel trong sub[]
							id_Hotel = json_data.getInt("id_Obj");
							// get id trip detail = id_TripHotel
							id_TripHotel = sendTripDetailHotel(id_Trip, n,
									hotelDes);
							// add res cho moi trip detail

							addRes(id_TripHotel, m[1]);
							addEvent(id_TripHotel, m[2]);
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						Toast.makeText(this, "EXception addHotel",
								Toast.LENGTH_SHORT).show();
					}
				}
			}
		}
	}

	private void addRes(int id, String a) {
		// TODO Auto-generated method stub
		String sub[] = a.split("\n"); // tach "res + time" tuong ung luu
										// vao sub[]
		for (int i = 1; i < sub.length; i++) {
			Log.v("SUB", sub[i]);
			String res[] = sub[i].split(" luc "); // tach res va time luu vao
													// res[], res[0] = res,
													// res[1] = time
			for (int j = 0; j < Restaurant.jArr.length(); j++) {
				try {
					JSONObject json_data = Restaurant.jArr.getJSONObject(j);
					String name2 = json_data.getString("name");
					if (res[0].equals(name2)) {
						id_Res = json_data.getInt("id_Obj");
						sendTripDetailResEvent(id, id_Res, res[1], 2);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}

	private void addEvent(int id, String a) {
		// TODO Auto-generated method stub
		String sub[] = a.split("\n"); // tach "res + time" tuong ung luu
										// vao sub[]
		for (int i = 1; i < sub.length; i++) {
			Log.v("SUB", sub[i]);
			String event[] = sub[i].split(" luc "); // tach res va time luu vao
													// res[], res[0] = res,
													// res[1] = time
			for (int j = 0; j < Event.jArr.length(); j++) {
				try {
					JSONObject json_data = Event.jArr.getJSONObject(j);
					String name2 = json_data.getString("name");
					if (event[0].equals(name2)) {
						id_Event = json_data.getInt("id_Obj");
						sendTripDetailResEvent(id, id_Event, event[1], 3);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}

	private int sendTripDetailResEvent(int id, int id_Obj, String time,
			int id_Type) {
		// TODO Auto-generated method stub

		int id_TripDetailHotel = 0;
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("id_TripDetail", Integer
				.toString(id)));
		postParameters.add(new BasicNameValuePair("id_Obj", Integer
				.toString(id_Obj)));
		postParameters.add(new BasicNameValuePair("time", time));
		postParameters.add(new BasicNameValuePair("id_Type", Integer
				.toString(id_Type)));

		// String valid = "1";
		String response = null;
		try {
			response = CustomHttpClient.executeHttpPost(Constant.host
					+ "/TripController/addTripDetailResEvent", postParameters);
			String res = response.toString();
			res = res.replaceAll("\\s+", "");
			// error.setText(res);
			if (Integer.parseInt(res) > 0) {
				Toast.makeText(this, "Insert res successful", Toast.LENGTH_SHORT)
						.show();
				id_TripDetailHotel = Integer.parseInt(res);
				startActivity(new Intent(this, Main.class));

			} else
				Toast.makeText(this, "Sorry!! Insert res not successful",
						Toast.LENGTH_SHORT).show();

		} catch (Exception e) {

		}
		return id_TripDetailHotel;
	}

	private int sendTripInfo() {
		// TODO Auto-generated method stub

		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters
				.add(new BasicNameValuePair("id_User", "" + Constant.user));
		postParameters.add(new BasicNameValuePair("dateStart", startDate
				.getText().toString()));
		postParameters.add(new BasicNameValuePair("name", tripName.getText()
				.toString()));

		// String valid = "1";
		String response = null;
		int id_Trip = 0;
		try {
			// response =
			// CustomHttpClient.executeHttpPost("http://192.168.1.110/Binh/TP/login.php",
			// postParameters);
			response = CustomHttpClient.executeHttpPost(Constant.host
					+ "/TripController/addTripInfo", postParameters);
			String res = response.toString();
			// res = res.trim();
			res = res.replaceAll("\\s+", "");
			// error.setText(res);
			if (Integer.parseInt(res) > 0) {
				Toast.makeText(this, "Insert successful", Toast.LENGTH_SHORT)
						.show();
				id_Trip = Integer.parseInt(res);
				// startActivity(new Intent(this, Main.class));

			} else
				Toast.makeText(this, "Sorry!! Insert not successful",
						Toast.LENGTH_SHORT).show();

		} catch (Exception e) {

		}
		return id_Trip;
	}

	private int sendTripDetailHotel(int id_Trip, int day, String des) {
		// TODO Auto-generated method stub
		int id_TripDetailHotel = 0;
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("id_Trip", Integer
				.toString(id_Trip)));
		postParameters
				.add(new BasicNameValuePair("day", Integer.toString(day)));
		postParameters.add(new BasicNameValuePair("id_Hotel", Integer
				.toString(id_Hotel)));
		postParameters.add(new BasicNameValuePair("description", des));

		// String valid = "1";
		String response = null;
		try {
			response = CustomHttpClient.executeHttpPost(Constant.host
					+ "/TripController/addTripDetailHotel", postParameters);
			String res = response.toString();
			res = res.replaceAll("\\s+", "");
			// error.setText(res);
			if (Integer.parseInt(res) > 0) {
				Toast.makeText(this, "Insert hotel successful",
						Toast.LENGTH_SHORT).show();
				id_TripDetailHotel = Integer.parseInt(res);
				startActivity(new Intent(this, Main.class));

			} else
				Toast.makeText(this, "Sorry!! Insert hotel not successful",
						Toast.LENGTH_SHORT).show();

		} catch (Exception e) {

		}
		return id_TripDetailHotel;
	}

	private void updateLabel() {
		if (date == null) {
			startDate.setText("" + dateAndTime.get(Calendar.YEAR) + "-"
					+ (dateAndTime.get(Calendar.MONTH) + 1) + "-"
					+ dateAndTime.get(Calendar.DAY_OF_MONTH));

		} else
			startDate.setText(date);
		// start_btn.setText(fmtDateAndTime.format(dateAndTime.DATE));
	}

	// for edit trip

}